/// 判断闰年
pub fn judge_leap_year(y: u32) -> bool {
    (y % 100 != 0 && y % 4 == 0) || (y % 400 == 0)
}

/// 查询指定年中有几天
pub fn get_days_in_year(y: u32) -> u32 {
    if judge_leap_year(y) {
        366
    } else {
        365
    }
}

/// 查询某一月中有几天
pub fn get_days_in_month(y: u32, m: u32) -> u32 {
    const MONTH_DAYS: [u32; 12] = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

    let mut days = MONTH_DAYS[m as usize - 1];
    if m == 2 && judge_leap_year(y) {
        days += 1;
    }

    days
}

/// 计算1970-01-01到所给日期的天数.
pub fn days_since_origin(y: u32, m: u32, d: u32) -> u32 {
    if y < 1970 {
        panic!("Can't handle date before 1970-01-01");
    }
    let mut days = 0;

    // 1968是闰年
    // 计算中间有几个完整的闰年
    let leap_year_num = (y - 1 - 1968) / 4;
    let to_dec_leap_year_num = (y - 1 - 1900) / 100; // 先认为每一百年就多算了一个闰年
    let to_inc_leap_year_num = (y - 1 - 1600) / 400; // 2001 会因为完整的 2000 而补上1天
    let leap_year_num = leap_year_num - to_dec_leap_year_num + to_inc_leap_year_num;
    // 完整年的天数
    days += 365 * (y - 1970) + leap_year_num;

    // 完整年的天数
    // for y in 1970..y {
    //     days += get_days_in_year(y);
    // }

    // 完整月份的天数
    for m in 1..m {
        days += get_days_in_month(y, m);
    }

    // 剩余天数
    days += d - 1;

    days
}
